unit DatabaseFunctionUnit;

interface

uses
  ADODB,
  DB,
  SysUtils;

procedure OpenDataSet(ASql: string; ADataSet: TADOQuery; AConnection: TADOConnection);
function GetSysParams(ParamKey: string; ADB: TADOConnection): string;
procedure SetSysParams(ParamKey, ParamValue: string; ADB: TADOConnection);

implementation

procedure OpenDataSet(ASql: string; ADataSet: TADOQuery; AConnection: TADOConnection);
begin
  ADataSet.Connection := AConnection;
  if not ADataSet.Connection.Connected then
    ADataSet.Connection.Connected := True;
  ADataSet.Close;
  ADataSet.SQL.Text := ASql;
  ADataSet.Open;  
end;

function GetSysParams(ParamKey: string; ADB: TADOConnection): string;
var
  Sql: string;
  query: TADOQuery;
begin
  query := TADOQuery.Create(nil);
  try
    Sql := 'SELECT ConfigValue FROM Config WHERE ConfigName = ''' + ParamKey + '''';
    OpenDataSet(Sql, query, ADB);
    if query.IsEmpty then
      Result := ''
    else
      Result := query.Fields[0].AsString;
  finally
    FreeAndNil(query);
  end;                
end;

procedure SetSysParams(ParamKey, ParamValue: string; ADB: TADOConnection);
var
  Sql: string;
  query: TADOQuery;
begin
  query := TADOQuery.Create(nil);
  try
    query.Connection := ADB;
    query.Close;
    query.SQL.Text := 'SELECT COUNT(*) FROM Config WHERE ConfigName = :key';
    query.Parameters.ParamByName('key').Value := ParamKey;
    query.Open;
    if query.Fields[0].AsInteger > 0 then
      Sql := 'UPDATE Config SET ConfigValue = :sc_value, UpdateTime = :time WHERE ConfigName = :sc_key'
    else
      Sql := 'INSERT INTO Config(ConfigName, ConfigValue, Updatetime) VALUES(:sc_key, :sc_value, :time)';
    query.Close;
    query.SQL.Text := Sql;
    query.Parameters.ParamByName('sc_key').Value := ParamKey;
    query.Parameters.ParamByName('sc_value').Value := ParamValue;
    query.Parameters.ParamByName('time').Value := Now;
    query.ExecSQL;
  finally
    FreeAndNil(query);
  end;
end;

end.
